﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Wiki.Entities;
using UMC.Web;

namespace UMC.Wiki.Activities
{
    class SubjectProjectItemActivity : WebActivity
    {
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var key = this.AsyncDialog("Key", g => this.DialogValue("EDITER"));
            var user = this.Context.Token.Identity();
            var sid = this.AsyncDialog("Id", d =>
            {
                if (request.SendValues == null || request.SendValues.ContainsKey("start") == false)
                {
                    var buider = new UISectionBuilder(request.Model, request.Command, request.Arguments);
                    buider.CloseEvent("UI.Event");
                    buider.RefreshEvent("Subject.ProjectItem");
                    this.Context.Send(buider.Builder(), true);
                }
                UITitle title = UITitle.Create();

                title.Title = "我参与的项目";
                switch (key)
                {
                    case "EDITER":
                        break;
                    default:
                        title.Title = "选择项目";
                        break;
                }

                var ui = UISection.Create(title);
                var projects = DataFactory.Instance().Projects(user.Id.Value, WebAuthType.Admin, WebAuthType.User);

                UMC.Data.Utility.Each(projects, dr =>
                {
                    ui.AddCell(dr.Caption, new UIClick(request, "Id", dr.Id.ToString()));

                });
                if (ui.Length == 0)
                {
                    ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "你未有编辑权限的项目").Put("icon", "\uF016"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),

                        new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));


                }

                response.Redirect(ui);

                return this.DialogValue("none");
            });
            var cmdId = UMC.Data.Utility.UInt64Parse(sid, 0);// ?? Guid.Empty;

            //var category = new ProjectItem();

            var category = DataFactory.Instance().ProjectItem(cmdId) ?? new ProjectItem();
            switch (key)
            {
                case "EDITER":
                    break;
                default:
                    this.Context.UIEvent(key, new ListItem(category.Caption, category.Id.ToString()), true);
                    break;
            }
            var projectId = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Project", g => this.DialogValue("Team"))).Value;

            var member = DataFactory.Instance().ProjectMember(projectId, user.Id.Value);

            if (member != null)
            {
                switch (member.AuthType)
                {
                    case WebAuthType.Admin:
                        break;
                    default:
                        this.Prompt("您未有编辑栏位权限");
                        break;
                }

            }
            else
            {
                this.Prompt("您未有编辑栏位权限");
            }

            var Caption = this.AsyncDialog("Caption", d =>
            {

                var fmdg = new Web.UIFormDialog();
                fmdg.Title = category.Id.HasValue ? "编辑栏位" : "新建栏位";
                fmdg.AddText("栏位名称", "Caption", category.Caption);
                if (category.Id.HasValue)
                {
                    fmdg.AddText("栏位简码", "Code", category.Code);
                    fmdg.AddCheckBox("", "Status", "NO").Put("隐藏", "Hide", category.Hide == true).Put("删除", "DEL");
                    fmdg.Submit("确认", "Subject.ProjectItem", "Subject.ProjectItem.Del");
                    fmdg.AddText("栏位关健字", "Keywords", category.Keywords).PlaceHolder("搜索引擎SEO优化").NotRequired();
                    fmdg.AddText("简短描述", "Description", category.Description).PlaceHolder("搜索引擎SEO优化").NotRequired();

                }
                else
                {
                    fmdg.Submit("确认", "Subject.ProjectItem", "Subject.ProjectItem.Del");

                }
                return fmdg;

            });
            var team = new ProjectItem();
            UMC.Data.Reflection.SetProperty(team, Caption.GetDictionary());

            if (category.Id.HasValue == false)
            {
                team.Id = UMC.Data.Utility.NewId();
                team.project_id = projectId;
                team.Code = UMC.Data.Utility.ParseEncode(UMC.Data.Utility.TimeSpan(), 36);// Utility.NewId());
                team.user_id = user.Id;
                team.CreationTime = DateTime.Now;
                team.Sequence = UMC.Data.Utility.TimeID();
                team.Hide = false;

                DataFactory.Instance().Put(team);

                var portfolio = new Portfolio()
                {
                    Id = UMC.Data.Utility.NewId(),
                    Caption = "随笔",
                    SubjectTotal = 0,
                    CreationTime = DateTime.Now,
                    Sequence = 0,
                    user_id = user.Id,
                    project_item_id = team.Id,
                    project_id = projectId,
                };
                DataFactory.Instance().Put(portfolio);

                DataFactory.Instance().Put(new ProjectDynamic
                {
                    Time = UMC.Data.Utility.TimeSpan(),
                    user_id = user.Id,
                    Alias = user.Alias,
                    Explain = "创建了栏位",
                    project_id = portfolio.project_id,
                    refer_id = portfolio.Id,
                    Title = portfolio.Caption,
                    Type = DynamicType.ProjectItem
                });
                var project = DataFactory.Instance().Project(projectId);
                this.Context.Send(new UMC.Web.WebMeta().Put("type", "Subject.ProjectItem").Put("id", team.Id).Put("text", team.Caption)
                    .Put("path", String.Format("{0}/{1}", project.Code, team.Code))
                    , true);

            }
            else
            {
                var status = Caption["Status"] ?? "";
                if (status.Contains("DEL"))
                {
                    var items = DataFactory.Instance().ProjectItem(new Project { Id = category.project_id.Value });
                    if (items.Length == 1)
                    {
                        this.Prompt("最少需要一个栏位");
                    }
                    var Portfolios = DataFactory.Instance().Portfolio(category);
                    switch (Portfolios.Length)
                    {
                        case 0:
                            break;
                        case 1:
                            if (DataFactory.Instance().Subject(Portfolios[0]).Length > 0)
                            {
                                this.Prompt("栏位下存在文章");
                            }
                            DataFactory.Instance().Delete(new Portfolio
                            {
                                project_item_id = category.Id
                            });
                            break;
                        default:
                            this.Prompt("栏位下存在文集");
                            break;
                    }



                    DataFactory.Instance().Delete(category);

                    DataFactory.Instance().Put(new ProjectDynamic
                    {
                        Time = UMC.Data.Utility.TimeSpan(),
                        user_id = user.Id,
                        Explain = "删除了栏位",
                        project_id = category.project_id,
                        refer_id = category.Id,
                        Alias = user.Alias,
                        Title = category.Caption,
                        Type = DynamicType.ProjectItem
                    });

                    this.Context.Send(new UMC.Web.WebMeta().Put("type", "Subject.ProjectItem.Del").Put("id", category.Id).Put("text", team.Caption), true);
                }
                else
                {
                    if (String.Equals(team.Code, category.Code, StringComparison.CurrentCulture) == false)
                    {
                        var exitItem = DataFactory.Instance().ProjectItem(category.project_id.Value, team.Code);
                        if (exitItem != null)
                        {
                            this.Prompt("存在相同的简码");
                        }

                    }
                    team.Id = category.Id;
                    team.Hide = status.Contains("Hide");
                    DataFactory.Instance().Put(team);
                    DataFactory.Instance().Put(new ProjectDynamic
                    {
                        Time = UMC.Data.Utility.TimeSpan(),
                        user_id = user.Id,
                        Explain = "修改了栏位",
                        Alias = user.Alias,
                        project_id = category.project_id,
                        refer_id = category.Id,
                        Title = category.Caption,
                        Type = DynamicType.ProjectItem
                    });
                    this.Context.Send(new UMC.Web.WebMeta().Put("type", "Subject.ProjectItem").Put("id", category.Id).Put("text", team.Caption).Put("hide", team.Hide), true);
                }
            }
            this.Prompt("修改成功");


        }


    }
}